package com.hongxun.project.assets.Tools;

import com.hongxun.framework.config.RuoYiConfig;
import com.hongxun.project.assets.bByq.controller.BByqController;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.usermodel.HeaderFooter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;

import java.io.*;

/**
 * Created by xhj on 2019/6/24.
 */
public class ExcelUtils {

    /**
     * 设置表单，并生成表单
     *
     * @param workbook
     * @param sheetName
     * @return
     */
    public static HSSFSheet genSheet(HSSFWorkbook workbook, String sheetName){
        //生成表单
        HSSFSheet sheet = workbook.createSheet(sheetName);
        //设置表单文本居中
        sheet.setHorizontallyCenter(true);
        sheet.setFitToPage(false);
        //打印时在底部右边显示文本页信息
        Footer footer = sheet.getFooter();
        footer.setRight( "Page " + HeaderFooter.numPages()+ " Of "+ HeaderFooter.page());
        //打印时在头部右边显示Excel创建日期信息
        Header header = sheet.getHeader();
        header.setRight("Create Date " + HeaderFooter.date() + " " + HeaderFooter.time());
        //设置打印方式
        HSSFPrintSetup ps = sheet.getPrintSetup();
        ps.setLandscape(true); // true：横向打印，false：竖向打印 ，因为列数较多，推荐在打印时横向打印
        ps.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE); //打印尺寸大小设置为A4纸大小
        return sheet;
    }

    /**
     * 创建文本样式
     *
     * @param workbook
     * @return
     */
    public static HSSFCellStyle genContextStyle(HSSFWorkbook workbook){
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);//文本水平居中显示
        style.setVerticalAlignment(VerticalAlignment.CENTER);//文本竖直居中显示
        style.setWrapText(true);//文本自动换行
        HSSFFont hssfFont = workbook.createFont();  //  设置正文字体大小
        hssfFont.setFontHeight((short)9);
        hssfFont.setFontHeightInPoints((short) 9);
        style.setFont(hssfFont);

        //生成Excel表单，需要给文本添加边框样式和颜色
        /*
             CellStyle.BORDER_DOUBLE      双边线
             CellStyle.BORDER_THIN        细边线
             CellStyle.BORDER_MEDIUM      中等边线
             CellStyle.BORDER_DASHED      虚线边线
             CellStyle.BORDER_HAIR        小圆点虚线边线
             CellStyle.BORDER_THICK       粗边线
         */

        style.setBorderBottom(BorderStyle.THIN);//设置文本边框
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        //set border color
        style.setTopBorderColor((short)8);//设置文本边框颜色
        style.setBottomBorderColor((short)8);
        style.setLeftBorderColor((short)8);
        style.setRightBorderColor((short)8);

        return style;
    }


    /**
     * 创建合并单元格的样式
     *
     * @param
     * @return
     */
    public static void setRegionStyle(BorderStyle border, CellRangeAddress region, Sheet sheet){
        RegionUtil.setBorderBottom(BorderStyle.THIN,region,sheet);
        RegionUtil.setBorderTop(BorderStyle.THIN,region,sheet);
        RegionUtil.setBorderLeft(BorderStyle.THIN,region,sheet);
        RegionUtil.setBorderRight(BorderStyle.THIN,region,sheet);
    }

    /**
     * 生成标题样式
     *
     * @param workbook
     * @return
     */
    public static HSSFCellStyle genTitleStyle(HSSFWorkbook workbook){

        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true);

        //标题居中，没有边框，所以这里没有设置边框，设置标题文字样式
        HSSFFont titleFont = workbook.createFont();
        titleFont.setBold(true);//加粗
        titleFont.setFontHeight((short)15);//文字尺寸
        titleFont.setFontHeightInPoints((short)15);
        style.setFont(titleFont);

        return style;
    }


    /**
     * 读取excel模板，并复制到新文件中供写入和下载
     *
     * @return
     */
    public File createNewFile(String fileName) {
        String name = "";
        if(fileName!="" || fileName!=null){
            name = fileName.substring(fileName.lastIndexOf("-")+1,fileName.length());
        }

        // 读取模板，并赋值到新文件
        // 文件模板路径
        String path = "";
        String classPaths = getClass().getResource("/").getPath();
        /*if(name.equals("资产表")){
            path = (getSispPath() + "bByq/temp/资产表.xls");
        }else if(name.equals("台账表")){
            path = (getSispPath() + "bByq/temp/台账表.xls");
        }else{
            path = (getSispPath() + "bByq/temp/变压器.xls");
        }*/

        if(name.equals("资产表")){
            path = (classPaths + "static/temp/zc.xls");
        }else if(name.equals("台账表")){
            path = (classPaths + "static/temp/tz.xls");
        }else{
            path = (classPaths + "static/temp/byq.xls");
        }
        File file = new File(path);
        // 保存文件的路径
//        RuoYiConfig.getDownloadPath();
//        String realPath = (getSispPath() + "template");
        String realPath = (RuoYiConfig.getDownloadPath() + "template");
        // 新的文件名
        String newFileName = fileName+"-" + System.currentTimeMillis() + ".xls";
        // 判断路径是否存在
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 写入到新的excel
        File newFile = new File(realPath, newFileName);
        try {
            newFile.createNewFile();
            // 复制模板到新文件
            fileChannelCopy(file, newFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFile;
    }
    /**
     * 下载成功后删除
     *
     * @param files
     */
    public static void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }



    /**
     * 复制文件
     *
     * @param s
     *            源文件
     * @param t
     *            复制到的新文件
     */
    public static void fileChannelCopy(File s, File t) {
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(s), 1024);
                out = new BufferedOutputStream(new FileOutputStream(t), 1024);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String getSispPath() {
//        String isa = request.getSession().getServletContext().getContextPath();
//        String classPaths = BByqController.class.getResource("/templates/assets/bByq/temp/").getPath();
        String classPaths = getClass().getResource("/").getPath();
        String[] aa = classPaths.split("/");
        String sispPath = "";
        for (int i = 1; i < aa.length - 2; i++) {
            sispPath += aa[i] + "/";
        }
        return sispPath;
    }


}
